<script lang="ts" setup>
import { ref, h, reactive, onMounted,onBeforeMount } from "vue";
import { ReVxeGrid } from "@/components/ReVxeTable";
import { VxeGridPropTypes, VxeUI } from "vxe-table";
import { VxeFormProps, VxeButton,VxeCheckbox,VxeImage } from "vxe-pc-ui";
import type {  FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { queryInvoiceListTax, getInvoiceOrderInfo, handleEditInvoiceOrderInfo } from "@/api/invoice/invoice";
import {
  MerchantsInfoByTaxSourcesId,
} from "@/api/welcome";
import { useRouter } from "vue-router";
const router = useRouter();
const reVxeGridRef = ref();
let taxSourcesId = Number(sessionStorage.getItem("taxSourcesId"))
onMounted(() => {
  getMerchantsInfoByTaxSourcesId( taxSourcesId )
});
interface RestaurantItem {
  id: number
  value: string
}
const listMerchantsInfoByTaxSourcesId = ref<RestaurantItem[]>([]);
const getMerchantsInfoByTaxSourcesId = (taxSourcesId?:
  number): void => {
  MerchantsInfoByTaxSourcesId(taxSourcesId).then((res: any) => {
    listMerchantsInfoByTaxSourcesId.value = res.data;
  });
};
const columns: VxeGridPropTypes.Columns<any> = [
  {
    title: "商户名称",
    field: "merchantsInfoIdDisplay",
    align: "center",
    minWidth: 100,
    showOverflow: true
  },
  {
    title: "税源地名称",
    field: "taxSourcesIdDisplay",
    align: "center",
    minWidth: 100,    
  }, 
  {
    title: "申请中金额",
    field: "amountInApplication",
    align: "center",
    minWidth: 100,    
  }, 
  {
    title: "可开票金额",
    field: "invoicingAmount",
    align: "center",
    minWidth: 60,    
  }, 
  {
    title: "累计开票金额",
    field: "cumulativeInvoiceAmount",
    align: "center",
    minWidth: 60,    
  }, 
  {
    title: "累计支出金额",
    field: "cumulativeExpenditureAmount",
    align: "center",
    minWidth: 60,    
  },   
  {
    title: "操作",
    field: "operate",
    align: "center",
    minWidth: 140,
    slots: {
      default: ({ row }) => {
        return [
          h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "开票记录",
              onClick() {
                router.push({
                  path: '/invoiceTax/record',
                  query: {
                    merchantsInfoId: row.merchantsInfoId
                  }
                })              
              }
            }),
            h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "编辑信息",
              onClick() {
                handleEditTaxInfo(row,'edit')             
              }
            })
          ]
      }
    }
  }
   
];
// 筛选相关
const formRef = ref();
interface FormDataVO {
  merchantsInfoId: string;//商户名称
  taxSourcesId: number | string; // 税源地 
  
}
const formOptions = reactive<VxeFormProps<FormDataVO>>({
  data: {
    merchantsInfoId: '',
    taxSourcesId: taxSourcesId
    
  },
  items: [
    {
      field: "merchantsInfoId",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "merchantsInfoId" }
    },        
    { align: "left", span: 4, slots: { default: "active" } }
  ]
});
// 重置内容
const handleInitialFormParams = () => {
  formOptions.data = <FormDataVO>{
    taxSourcesId: '',
    merchantsInfoId: '', 
  };
};
const handleSearch = () => {
  reVxeGridRef.value.loadData();
};
const handleReset = async () => {
  await handleInitialFormParams();
  reVxeGridRef.value.loadData("reset");
};

const handleView = (record: Recordable) => {
  
};
const functions: Record<string, string> = {
  add: "platform.client.index.add",
  edit: "platform.client.index.edit",
  view: "platform.client.index.view",
  delete: "platform.client.index.delete"
};
const editContentShow = ref(false);
function handleEditTaxInfo(row,type){
    editContentShow.value = true;
    getdetail(row)
}
const getdetail = (data) =>{
  getInvoiceOrderInfo({
    merchantsInfoId: data.merchantsInfoId,
    taxSourcesId: data.taxSourcesId
  }).then((res:any) =>{
    // ruleForm.value = res.data
    if(res.data){
       for (let key in ruleForm) {
        if (res?.data[key] === null || res?.data[key] === undefined) { 

        }else{
          ruleForm[key] = res?.data[key]
        }
      }
    }
  })
}

interface RuleForm { 
  taxSourcesId:string, 
  merchantsInfoId:string,
   merchantsName: string,
  enterpriseIdNumber: string,
  enterpriseRegistrationAddress:string,
  workTelephone:string,
  shippingAddress:string,
  nameOfRecipient:string,
  contactNumber:string,
  openingBank:string,
  bankAccount:string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  taxSourcesId:taxSourcesId,
  merchantsInfoId:'',
  merchantsName: '',
  enterpriseIdNumber: '',
  enterpriseRegistrationAddress:'',
  workTelephone:'',
  shippingAddress:'',
  nameOfRecipient:'',
  contactNumber:'',
  openingBank:'',
  bankAccount:''
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      handleEditInvoiceOrderInfo(ruleForm).then(res=>{

        queryInvoiceListTax(formOptions.data)
        editContentShow.value = false;
        
        ElMessage.success("修改保存成功!");
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const toback = ()=>{
  router.back();
}
</script>
<template>
  <div>
    <el-card :shadow="`never`">
      <vxe-form ref="formRef" v-bind="formOptions">
        <template #merchantsInfoId="{ data }">
          <el-select
            clearable
            placeholder="请选择商户名称"
            v-model="data.merchantsInfoId"
          >
            <el-option
              v-for="(item, index) in listMerchantsInfoByTaxSourcesId"
              :key="index"
              :label="item.value"
              :value="item.id"
            ></el-option>
          </el-select>
        </template>
        <template #active>
          <el-button @click="handleSearch" native-type="submit" type="primary"
            >搜索</el-button
          >
          <el-button @click="handleReset" native-type="reset">重置</el-button>          
        </template>
      </vxe-form>
    </el-card>
    <el-card :shadow="`never`" class="table-card">
      <ReVxeGrid
        ref="reVxeGridRef"
        :request="queryInvoiceListTax"
        :functions="functions"
        :searchParams="formOptions.data"
        :columns="columns"
        :action="false"
        @handleView="handleView"
      />
    </el-card>
    <el-dialog
      v-model="editContentShow"
      title="编辑信息"
      width="500"
      :destroy-on-close="true"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
        <el-row>
          <el-col :span="24">
            <div>开票信息</div>
          </el-col>
          <el-col :span="19" :offset="1">
            <el-form-item label="企业名称">
              <el-input v-model="ruleForm.merchantsName" placeholder="企业名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="19" :offset="1">
            <el-form-item label="纳税人识别号">
              <el-input v-model="ruleForm.enterpriseIdNumber" placeholder="纳税人识别号"/>
            </el-form-item>
          </el-col>
          <el-col :span="19" :offset="1">
            <el-form-item label="企业注册地址">
              <el-input v-model="ruleForm.enterpriseRegistrationAddress" placeholder="企业注册地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="19" :offset="1">
            <el-form-item label="单位电话">
              <el-input v-model="ruleForm.workTelephone" placeholder="单位电话"/>
            </el-form-item>
          </el-col>
          <el-col :span="19" :offset="1">
            <el-form-item label="开户行">
              <el-input v-model="ruleForm.openingBank" placeholder="开户行"/>
            </el-form-item>
          </el-col>
          <el-col :span="19" :offset="1">
            <el-form-item label="银行账号">
              <el-input v-model="ruleForm.bankAccount" placeholder="银行账号"/>
            </el-form-item>
          </el-col>
         <el-col :span="24">
            <div>邮寄地址</div>
          </el-col>
          <el-col :span="19" :offset="1">
            <el-form-item label="收货地址">
              <el-input v-model="ruleForm.shippingAddress" placeholder="收货地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="19" :offset="1">
            <el-form-item label="收件人姓名">
              <el-input v-model="ruleForm.nameOfRecipient" placeholder="收件人姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="19" :offset="1">
            <el-form-item label="联系电话">
              <el-input v-model="ruleForm.contactNumber" placeholder="联系电话"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
            <div class="flex justify-end items-center flex-1">
              <el-button type="primary" @click="submitForm(ruleFormRef)">
                保存
              </el-button>
            </div>
          </el-form-item>
          </el-col>
        </el-row>
          
          
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<style>
</style>
